<script setup lang="tsx">
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import MyTable from '@/components/myTable/index.vue';
import OperatingBox from '@/components/operatingBox/index.vue';
import QueryBox from '@/components/queryBox/index.vue';
import { formGroup } from '@/components/formDialog/FormDialog';
import FormDialogGroup from '@/components/formDialog/FormDialogGroup.vue';
import { Space, Link, MessagePlugin } from 'tdesign-vue-next';
import { AddIcon, Delete1Icon } from 'tdesign-icons-vue-next';
import { getLangList, add, edit, getInfo, Delete } from '@/api/system/basicSetting/7';

const { t } = useI18n();

const data = ref([]);
const columns = [
  {
    colKey: 'row-select',
    type: 'multiple' as const,
    width: 50,
  },
  {
    title: 'ID',
    colKey: 'id',
  },
  {
    title: '标签',
    colKey: 'name',
  },
  {
    title: '键值',
    colKey: 'code',
  },
  {
    title: '排序',
    colKey: 'sortBy',
  },
  {
    title: '状态',
    colKey: 'status',
  },
  {
    title: '创建时间',
    colKey: 'createTime',
  },
  {
    title: '操作',
    colKey: 'op',
  },
];

const pagination = ref({
  defaultCurrent: 1,
  defaultPageSize: 10,
  total: 0,
});

const render = () => (
  <>
    <OperatingBox style="margin-bottom: 20px;padding: 0;">
      <t-button icon={() => <AddIcon />} onClick={() => unAdd()}>
        新增
      </t-button>
      <t-button theme="danger" icon={() => <Delete1Icon />} onClick={() => deleteClickOp(deleteId.value, true)}>
        批量删除
      </t-button>
    </OperatingBox>
    {/* <QueryBox style="margin-bottom: 20px;padding: 0;"></QueryBox> */}
    <MyTable
      columns={columns}
      data={data.value}
      v-model:pagination={pagination.value}
      v-model:selectedRowKeys={deleteId.value}
      rowKey="id"
      onUnGetList={unGetUserList}
    >
      {{
        status: (slotProps: any) => (
          <t-tag theme={slotProps.row.status == 1 ? 'primary' : 'danger'} variant="light">
            {slotProps.row.status == 1 ? '正常' : '停用'}
          </t-tag>
        ),
        op: (slotProps: any) => (
          <Space>
            <Link theme="primary" onClick={() => unEdit(slotProps)}>
              修改
            </Link>
            <Link theme="danger" onClick={() => deleteClickOp(slotProps, false)}>
              {t('pages.detailCard.detail.form.delete')}
            </Link>
          </Space>
        ),
      }}
    </MyTable>
  </>
);

const unGetUserList = async () => {
  try {
    const res = await getLangList({
      pageNum: pagination.value.defaultCurrent,
      pageSize: pagination.value.defaultPageSize,
    });
    data.value = res.rows;
    pagination.value = {
      ...pagination.value,
      total: res.total,
    };
  } catch (e) {
    console.log(e);
  }
};

unGetUserList();

/** 添加对话框 */
const formObj = new formGroup();
const unAdd = async () => {
  try {
    formObj.show('添加语言', {}, '添加语言');
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};
formObj.add<any>(
  '添加语言',
  '添加语言',
  {
    data: {
      status: 0,
    },
  },
  async (body) => {
    await add(body.data);
    unGetUserList();
  },
  {
    nickName: [{ required: true, message: '语言昵称不能为空', trigger: 'blur' }],
    userName: [{ required: true, message: '语言名称不能为空', trigger: 'blur' }],
    password: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      {
        validator: (val: string) => val.length >= 5 && val.length <= 20,
        message: '密码长度应介于5至20位之间',
        trigger: 'blur',
      },
    ],
  },
);

// 语言详情
const unEdit = async (slotProps: any) => {
  try {
    let res = await getInfo(slotProps.row.id);
    formObj.show(
      '编辑语言',
      {
        ...res.data,
      },
      '编辑语言',
    );
  } catch (e) {
    console.error('获取语言详情失败:', e);
    MessagePlugin.error('获取语言详情失败');
  }
};

formObj.add<any>(
  '编辑语言',
  '编辑语言',
  {},
  async (body) => {
    await edit(body.data);
    unGetUserList();
  },
  {
    // nickName: [
    //     { required: true, message: '语言昵称不能为空', trigger: 'blur' },
    //   ],
  },
);

// 删除
const confirmVisible = ref(false);
const deleteId = ref([]);
const onConfirmDelete = () => {
  let ids = deleteId.value.join(',');
  Delete(ids).then(() => {
    confirmVisible.value = false;
    MessagePlugin.success('删除成功');
    unGetUserList();
  });
};

const deleteClickOp = (value: any, isSingle: boolean) => {
  if (isSingle && !value.length) {
    MessagePlugin.warning('请先勾选数据');
    return;
  }
  confirmVisible.value = true;
  deleteId.value = isSingle ? value : [value.row.id];
};

const onCancel = () => {
  if (deleteId.value.length < 2) {
    deleteId.value = [];
  }
};
</script>

<template>
  <div class="box">
    <render />
    <!-- 对话框 -->
    <FormDialogGroup :form-obj="formObj">
      <template #default="{ formData, item }">
        <template v-if="item == '添加语言' || item == '编辑语言'">
          <t-form-item label="标签" name="name">
            <t-input v-model="formData.name" placeholder="标签" />
          </t-form-item>
          <t-form-item label="键值" name="code">
            <t-input v-model="formData.code" placeholder="键值" />
          </t-form-item>
          <t-form-item label="排序" name="sortBy">
            <t-input-number v-model="formData.sortBy" :min="0" />
          </t-form-item>
          <t-form-item label="状态" name="status">
            <t-radio-group v-model="formData.status">
              <t-radio :value="1">正常</t-radio>
              <t-radio :value="0">停用</t-radio>
            </t-radio-group>
          </t-form-item>
        </template>
      </template>
    </FormDialogGroup>
    <t-dialog
      v-model:visible="confirmVisible"
      header="确认删除当前所选项目？"
      body="删除后，数据将被清空，且无法恢复"
      @confirm="onConfirmDelete"
      :on-cancel="onCancel"
    />
  </div>
</template>

<style lang="less" scoped>
.box {
  padding: 20px;
}
</style>
